package com.k2data.k2app.service.pas04;

import com.k2data.k2app.domain.pasObject.PasProject;
import com.k2data.k2app.domain.pasObject.Select;
import com.k2data.k2app.domain.po.TaskDTO;
import com.k2data.k2app.domain.vo.Model;
import com.k2data.k2app.exception.K2ResponseException;
import com.k2data.k2app.util.DateFormatterUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 预警处理
 * Created by clb on 17-4-18.
 */
@Log4j2
@Service
public class Model04Service {

	@Autowired
	private Pas04ProjectService pas04ProjectService;

	/**
	 * 根据 [id] 查询
	 * @param modelId
	 * @return
	 * @throws Exception
	 */
	public Model get(Long modelId)  throws Exception{
		PasProject pasProject = pas04ProjectService.getPasProject(modelId);
		if(pasProject == null){
			return null;
		}
		Model model = projectToModel(pasProject);
		return model;
	}

	/**
	 * 列表
	 * @return
	 * @throws Exception
	 */
	public List<Model> list () throws Exception {
		//1 pasProjects
		List<PasProject> pasProjects = pas04ProjectService.getPasProjects();
		//2 转为model
		List<Model> models = projectsToModels(pasProjects);
		return models;
	}

	/**
	 * 复制并且编辑模型
	 * @param taskDO
	 * @return
	 */
	public Long copyAndEdit(TaskDTO taskDO) throws Exception {
		//1 复制pas项目
		PasProject pasProject = pas04ProjectService.copyPasProject(taskDO.getModelId());
		//2 编辑pas项目
		pasProject = editProject(pasProject,taskDO);
		//2.1 修改owner
		String owner = pasProject.getOwner();
		pasProject.setOwner(String.format("%s_%s",owner,"copy"));
		//3 创建pas项目
		String info = pas04ProjectService.createProject(pasProject);
		return Long.parseLong(info);
	}

	public PasProject editProject(PasProject pasProject,TaskDTO taskDO){
		//2.1 修改表
		// TODO groupId
		String groupId = "";
//		String groupId = taskDO.getPointData().getValue();
		pasProject.getProjectConf().setStmtTable("["+groupId+"]");
		//2.12 修改表选择的字段
		List<Select> selects = pasProject.getProjectConf().initSelect();
		taskDO.getVarData().stream().forEach(item -> {
			if(!item.getLabel().toLowerCase().equals("deviceno") && !item.getLabel().toLowerCase().equals("ts")){
				Select select = new Select();
				select.setName(item.getLabel());
				select.setType(item.getValue());
				selects.add(select);
			}
		});
		pasProject.getProjectConf().setSelect(selects);
		//2.2 修改抽取条件
		List<Map> conditions = new ArrayList<>();
		Map<String,Object> condition = new HashMap<>();
		Optional<String> deviceno = Optional.ofNullable(taskDO.getDevice().get(0)).map(s -> s.getDeviceNo());
		deviceno.ifPresent(s-> condition.put("deviceNo",deviceno.get()));
		String from = DateFormatterUtil.parseToString(taskDO.getStartDate(),DateFormatterUtil.dateTimeFormatter);
		String to = DateFormatterUtil.parseToString(taskDO.getEndDate(),DateFormatterUtil.dateTimeFormatter);
		List<Map> listTs = new ArrayList<>();
		Map mapTime = new HashMap();
		mapTime.put("from",from);
		mapTime.put("to",to);
		listTs.add(mapTime);
		condition.put("ts",listTs);
		conditions.add(condition);
		pasProject.getProjectConf().setPartitionInfo(conditions);
		//2.4 修改输出条件
		Optional<String> optional1 = Optional.ofNullable(taskDO.getKmxSumField());
		optional1.ifPresent(s -> {
			String[] fields = s.split("#");
			String field = fields[1];
			Optional<String> tab = Optional.ofNullable(pasProject.getProjectConf().getCustomConf()).map(o -> o.get("pas.target.tabinfo")).map(t -> t.toString());
			tab.ifPresent(t -> {
				String[] tds = t.split(",");
				if(tds.length==3){
					String newColumnName = "";
					for(String td:tds){
						if(!td.startsWith("ts")&&!td.startsWith("deviceNo")){
							String[] columns = td.split(" ");
							String columnTab = String.format("%s %s",field,columns[1]);
							newColumnName =  newColumnName.equals("")?columnTab:String.format("%s,%s",newColumnName,columnTab);
						}else{
							newColumnName = newColumnName.equals("")?td:String.format("%s,%s",newColumnName,td);
						}
					}
					pasProject.getProjectConf().getCustomConf().put("pas.target.tabinfo",newColumnName);
				}
			});
		});
		return pasProject;
	}


	/**
	 * 编辑pas项目
	 */
	public Long edit(TaskDTO taskDO) throws Exception{
		if(taskDO.getModelIdCopy() == null){
			return null;
		}
		//1 获取pas项目
		PasProject pasProject = pas04ProjectService.getPasProject(taskDO.getModelIdCopy());
		PasProject pasProject1 = editProject(pasProject,taskDO);
		pas04ProjectService.editProject(pasProject1);
		return taskDO.getModelIdCopy();
	}
	
	public Long run(Long projectId,String deviceNo,String start,String end) throws Exception {
		Map<String,String> params = new HashMap<>();
		params.put("jobName",pas04ProjectService.getJobName());
		params.put("overrideStmtWhere","deviceNo ='"+deviceNo+"' " +
				" and ts >= '"+start+
				"' and ts < '"+end+"'");
		String jobId = pas04ProjectService.runProject(projectId,params);
		return Long.parseLong(jobId);
	}

	public void delete(Long projectId) throws Exception {
		pas04ProjectService.deleteProjectById(projectId);
	}

	/**
	 * pas项目转为model
	 */
	public List<Model> projectsToModels(List<PasProject> pasProjects) throws Exception {
		List<Model> models = new ArrayList<>();
		for(PasProject pasProject:pasProjects){
			Model model = projectToModel(pasProject);
			models.add(model);
		}
		return models;
	}

	/**
	 * pas项目转换为本地模型对象
	 * @param pasProject
	 * @return
	 * @throws K2ResponseException
	 */
	public Model projectToModel(PasProject pasProject) throws K2ResponseException {
		String id = pasProject.getProjId();
		Model model = new Model();
		model.setName(pasProject.getProjName());
		model.setShortDesc(pasProject.getDescription());
		model.setId(Long.parseLong(id));
		model.setAnalysisType(pasProject.getProjectConf().getAnalysisType());
		model.setDataSource(pasProject.getProjectConf().getDataSource());
		Date createDate = new Date(Long.parseLong(pasProject.getCreateTime()));
		Date updateDate = new Date(Long.parseLong(pasProject.getUpdateTime()));
		model.setUpdateTime(DateFormatterUtil.UDateToLocalDateTime(updateDate));
		model.setCreateTime(DateFormatterUtil.UDateToLocalDateTime(createDate));
		model.setOwner(pasProject.getOwner());
		model.setDownloadUrl(pas04ProjectService.getURI(pas04ProjectService.getDownLoadUrl(Long.parseLong(id),pasProject.getProjectConf().getMainR())));
		return model;
	}
}
